<?php

// Prevent individual file access
if(!defined('DIR_BASE')) exit;

/**
 * Loader for classes/packages
 */
class Loader{
	
	/**
	 * Try to import a specified file
	 * @param String $path The given path
	 * @param String $filename The given filename without the extention
	 * @return Bool Success
	 */
	private static function _importFile($path, $filename){
		if(is_file($path.$filename.'.php')){
			require_once($path.$filename.'.php');
			return true;
		}else return false;
	}
	
	/**
	 * Import a package or file
	 * @param String|Array $components A component path
	 * @return Bool Success
	 */
	public static function import($components){
		if(!is_array($components))
			$components = explode('.', $components);
		
		// quit if there are no components given
		if(sizeof($components) == 0)
			return false;
		
		// guess the path of the file
		$path = '';
		if(defined('DIR_'.strtoupper($components[0])))
			$path = constant('DIR_'.strtoupper(array_shift($components)));
		else
			$path = DIR_BASE;
			
		foreach($components as $component){
			// try to import a package of files
			if($component == '*'){
				if(is_dir($path)){
					$files = scandir($path);
					$loaded = 0;
					foreach($files as $file){
						if(self::_importFile($path, preg_replace("/\\.[^.\\s]{3,4}$/", "", $file)))
							$loaded++;
					}
					return ($loaded > 0);
				}
				else return false;
			}
			// try to import a stand-alone file
			else{
				if(!self::_importFile($path, $component))
					$path .= $component.DS;
				else return true;
			}
		}
		// nothing has worked
		return false;
	}
}

/**
 * Shortcut function to import
 * @see Loader::import
 */
function import($components){
	return Loader::import($components);
}

?>